﻿using Framework.EncryptionService.Attributes;
using Framework.EncryptionService.Services;
using Microsoft.AspNetCore.Http;
using System.Net;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace Framework.EncryptionService
{
    /// <summary>
    /// 入参解密
    /// </summary>
    public class InputDecryption
    {
        /// <summary>
        /// 入参解密
        /// </summary>
        /// <param name="requestBody">入参信息</param>
        /// <param name="endpointFeature">不加密特性</param>
        /// <returns>入参解密实体</returns>
        public static DecryptionModels InputDecryptionHelps(HttpContext context, NonEncryptedAttribute endpointFeature)
        {
            DecryptionModels decryption = new() { Code = 0, Message = "Success." };

            //验证Header是否存在SecretKey 秘钥
            context.Request.Headers.TryGetValue("SecretKey", out Microsoft.Extensions.Primitives.StringValues value);
            EncryptionRSAServiceHelps encryption = new EncryptionRSAServiceHelps();
            //解密AES
            EncryptionServiceHelpsEntity decReq = null;
            if (!string.IsNullOrWhiteSpace(value))
            {
                decReq = encryption.Decrypt<EncryptionServiceHelpsEntity>(value);
                //添加前端AES秘钥到会话中
                decryption.AesSecret = decReq.ConvertToString();
            }

            //没有实现“NonEncryptedAttribute”特性，或者 特性中加密方式为“请求加密”、或“全部加密”时需要将入参解密
            if (endpointFeature == null || endpointFeature.EncryptionTypes == EncryptionType.Request || endpointFeature.EncryptionTypes == EncryptionType.Full)
            {
                if (decReq == null || string.IsNullOrEmpty(decReq.PublicSecretKey) || string.IsNullOrEmpty(decReq.PrivateSecretKey))
                {
                    decryption.Code = 400;
                    decryption.Message = "秘钥错误";
                    return decryption;
                }
                //获取接口请求入参信息
                string requestBody = GetRequestBody(context, endpointFeature).Result;
                // 假设入参是 JSON 格式，这里进行简单的 JSON 解析和校验
                if (!string.IsNullOrEmpty(requestBody))
                {
                    try
                    {
                        //使用AES秘钥解密入参信息
                        EncryptionAESServiceHelps encryptionAES = new EncryptionAESServiceHelps(decReq);

                        byte[] newRequestBody = encryptionAES.Decrypt(requestBody).ConvertToBytes();
                        decryption.Body = new MemoryStream(newRequestBody);
                    }
                    catch (Exception ex)
                    {
                        decryption.Code = 400;
                        decryption.Message = $"入参解密失败: {ex.Message}";
                    }
                }
            }

            return decryption;
        }

        /// <summary>
        /// 获取接口请求入参信息
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public static async Task<string> GetRequestBody(HttpContext context, NonEncryptedAttribute endpointFeature)
        {
            // 从请求中获取入参信息
            string requestBody = "";
            using (var ms = new MemoryStream())
            {
                await context.Request.Body.CopyToAsync(ms);
                var buffer = ms.ToArray();
                ms.Position = 0;

                using (var reader = new StreamReader(ms))
                {
                    requestBody = await reader.ReadToEndAsync();
                    if (!string.IsNullOrWhiteSpace(requestBody))
                    {
                        // 将流指针重置到开始位置，以便后续中间件或控制器能够正常读取
                        ms.Position = 0;
                    }
                }
            }
            return requestBody;
        }
    }
}
